//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力 
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    // 获取系统信息 
    wx.getSystemInfo({
      success: e => {
        this.globalData.systemInfo = e;
      }
    })

    const that = this
    wx.checkSession({
      success() {
        //session_key 未过期，并且在本生命周期一直有效
        // 验证token是否过期
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        that.xiaohuangyu_login()
      }
    })
    // token验证
    that.verify_token()
  },
  xiaohuangyu_login() {
    //重新登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        const data = { code: res.code }
        this.post('/member/wechat/code2session/', data, rqres => {
          if (rqres.status) {
            wx.setStorageSync('token', rqres.data.token)
            this.globalData.userInfo = rqres.data.userInfo
            console.log('userInfo', this.globalData.userInfo)
            // // 获取用户信息
            // wx.getSetting({
            //   success: res => {
            //     if (res.authSetting['scope.userInfo']) {
            //       // 已经授权，可以直 接调用 getUserInfo 获取头像昵称，不会弹框
            //       wx.getUserInfo({
            //         success: res => {
            //           console.log('userInfo11111111111', this.globalData.userInfo)
            //           // 可以将 res 发送给后台解码出 unionId
            //           this.globalData.userInfo = res.userInfo
            //           // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            //           // 所以此处加入 callback 以防止这种情况
            //           if (this.userInfoReadyCallback) {
            //             this.userInfoReadyCallback(res)
            //           }
            //         }
            //       })
            //     }
            //   }
            // })
          }
        })
      }
    })
  },

  // 验证token
  verify_token() {
    console.log('-------verify_token---------')
      wx.request({
        url: this.globalData.rootDocment + '/member/user_info/',
        header: {
          'Authorization': 'JWT ' + wx.getStorageSync('token') || ''
        },
        method: 'get',
        complete: (res) => {
          if (res.statusCode !== 200) {
            wx.setStorageSync('token', '')
            console.log('-------verify_token--过期重新登录-------')
            this.xiaohuangyu_login()
          }else{
            this.globalData.userInfo = res.data.data
          }
        }
      })
  },
  towxml: require('./towxml/index'),
  globalData: {
    userInfo: null,
    token: '',
    systemInfo: null,
    rootDocment: 'http://192.168.2.165:8400',
    qqmapsdk_key: 'LR4BZ-LBTKU-A7VVG-2TVAW-SXWTV-PLBK2'
  },

  post: function (url, data, cb, method = 'post') {
    this.Request(url, data, method, {}, cb)
  },
  get: function (url, data, cb,) {
    // let headder = { 'Content-Type': 'application/x-www-form-urlencoded' }
    this.Request(url, data, 'get', {}, cb)
  },
  delete: function (url, cb, data = {}) {
    this.Request(url, data, 'delete', {}, cb)
  },

  uploadFile: function (filePath, path, cb) {
    var token = wx.getStorageSync('token') || ''
    var header = {}
    if (token) {
      header['Authorization'] = 'JWT ' + token
    }
    wx.uploadFile({
      url: this.globalData.rootDocment + '/member/upload_image/', //仅为示例，非真实的接口地址
      filePath: filePath,
      name: 'file',
      header: header,
      formData: {
        'path': path
      },
      success(res) {
        if (res.statusCode === 200) {
          return typeof cb == "function" && cb(res.data)
        } else {
          wx.showModal({
            title: '提示',
            content: '网络错误，请重启小程序',
            showCancel: false
          })
        }
      }
    })
  },

  // 请求
  Request: function (url, data, method, header, cb) {
    var token = wx.getStorageSync('token') || ''
    if (token) {
      header['Authorization'] = 'JWT ' + token
    }
    wx.request({
      url: this.globalData.rootDocment + url,
      data: data,
      method: method,
      header: header,
      complete: (res) => {
        console.log('request.res', res)
        if (res.statusCode === 200) {
          return typeof cb == "function" && cb(res.data)
        } else if (res.statusCode === 400) {
          console.log(res.data.message)
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '网络错误，请重启小程序',
            showCancel: false
          })
        }
      }
    })
  }
})